using DevExpress.XtraEditors;
using Shopfloormanagement;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using DocumentFormat.OpenXml.Drawing;
using Drawing = DocumentFormat.OpenXml.Drawing;
using D = DocumentFormat.OpenXml.Drawing;
using P = DocumentFormat.OpenXml.Presentation;



namespace Shopfloormanagement
{
    public partial class projectReport : DevExpress.XtraEditors.XtraForm
    {

        //要制作报告的ID
        public static int reportID = 0;
        //只能保存
        private bool isDirty = false;

        public projectReport()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
            xtraTabControl1.ShowTabHeader = DevExpress.Utils.DefaultBoolean.False;

        }

        private void projectReport_Load(object sender, EventArgs e)
        {
            //载入基本信息
            DataTable dt = LSQL.SQL.ReturnDataTable3(SystemInfo.SQL, "CIP_list", $"delTag=0 and [PID]={reportID} order by ID");
            if (dt.Rows.Count > 0)
            {
                textTopic.Text = dt.Rows[0]["Topic"].ToString();
                textOwner.Text = dt.Rows[0]["Owner"].ToString();
                string base64StringBefore = dt.Rows[0]["beforePic"].ToString();
                string base64StringAfter = dt.Rows[0]["afterPic"].ToString();
                richTextBoxBefore.Text = dt.Rows[0]["beforeText"].ToString();
                richTextBoxAfter.Text = dt.Rows[0]["afterText"].ToString();

                if (!string.IsNullOrEmpty(base64StringBefore))
                {
                    pictureEditBefore.Image = CovertBase64ToImage(base64StringBefore);
                }

                if (!string.IsNullOrEmpty(base64StringAfter))
                {
                    pictureEditAfter.Image = CovertBase64ToImage(base64StringAfter);
                }
            }
            //只能检测用
            richTextBoxBefore.TextChanged += (s, e1) => isDirty = true;
            richTextBoxAfter.TextChanged += (s, e2) => isDirty = true;
            pictureEditBefore.ImageChanged += (s, e3) => isDirty = true;
            pictureEditAfter.ImageChanged += (s, e4) => isDirty = true;


        }

        private void btnSave_Click(object sender, EventArgs e)
        {
           
            isDirty = false;
            //录入
            string pic1_Str = ConvertImageToBase64(pictureEditBefore);
            string pic2_Str = ConvertImageToBase64(pictureEditAfter);

            string updateContent = $"[beforePic]='{pic1_Str}', [afterPic]='{pic2_Str}', [beforeText]='{richTextBoxBefore.Text}', [AfterText]='{richTextBoxAfter.Text}'";
            string condition = $"[PID]={reportID} and delTag=0";

            if (LSQL.SQL.Update(SystemInfo.SQL, "CIP_list", updateContent, condition))
                
                
            {
                MessageBox.Show("Save successful", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }





        }

        private string ConvertImageToBase64(PictureEdit pic)   //图片转换为Base64
        {
            if (pic.Image == null)
            {
                return null;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                pic.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                byte[] imageBytes = ms.ToArray();
                return Convert.ToBase64String(imageBytes);

            }


        }

        private Image CovertBase64ToImage(string base64String)  //Base64转化为图片
        {
            try
            {
                // 将 Base64 字符串解码为字节数组
                byte[] imageBytes = Convert.FromBase64String(base64String);

                // 使用 MemoryStream 将字节数组转换为 Image 对象
                using (MemoryStream ms = new MemoryStream(imageBytes))
                {
                    Image image = Image.FromStream(ms);
                    return image;
                }
            }
            catch (Exception ex)
            {

                // 处理异常（例如 Base64 字符串格式错误）
                throw new Exception("Base64 字符串转换失败: " + ex.Message);
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                // 1. 验证Topic不为空
                if (string.IsNullOrWhiteSpace(textTopic.Text))
                {
                    XtraMessageBox.Show("Please fill in the project name (Topic)");
                    return;
                }

                // 2. 准备桌面路径
                string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                string pptName = $"{textTopic.Text.Trim()}.pptx";
                string outputPath = System.IO.Path.Combine(desktopPath, pptName);

                // 3. 检查文件是否已存在
                if (File.Exists(outputPath))
                {
                    if (XtraMessageBox.Show("File already exists, do you want to overwrite?", "Confirm", MessageBoxButtons.YesNo) != DialogResult.Yes)
                        return;
                }

                // 4. 从资源中获取模板并创建临时文件
                string tempTemplatePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "Template.pptx");
                try
                {
                    // 将资源中的模板写入临时文件
                    File.WriteAllBytes(tempTemplatePath, Properties.Resources.Template);
                    
                    // 5. 复制模板文件到目标位置
                    File.Copy(tempTemplatePath, outputPath, true);

                    // 6. 替换内容
                    using (PresentationDocument ppt = PresentationDocument.Open(outputPath, true))
                    {
                        SlidePart slidePart = ppt.PresentationPart.SlideParts.First();

                        // 替换文本
                        ReplaceTextPlaceholder(slidePart, "[Topic]", textTopic.Text);
                        ReplaceTextPlaceholder(slidePart, "[Owner]", textOwner.Text);
                        ReplaceTextPlaceholder(slidePart, "[BeforeText]", richTextBoxBefore.Text);
                        ReplaceTextPlaceholder(slidePart, "[AfterText]", richTextBoxAfter.Text);

                        // 替换图片
                        ReplaceImagePlaceholder(slidePart, "BeforeImage", pictureEditBefore.Image);
                        ReplaceImagePlaceholder(slidePart, "AfterImage", pictureEditAfter.Image);
                    }

                    XtraMessageBox.Show($"PPT successfully exported to：\n{outputPath}", "Completed");
                }
                finally
                {
                    // 清理临时文件
                    if (File.Exists(tempTemplatePath))
                    {
                        try
                        {
                            File.Delete(tempTemplatePath);
                        }
                        catch { /* 忽略删除临时文件时的错误 */ }
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"Export failed: {ex.Message}", "Error");
            }
        }
        private void ReplaceTextPlaceholder(SlidePart slidePart, string placeholder, string newText)
        {
            foreach (var shape in slidePart.Slide.Descendants<DocumentFormat.OpenXml.Presentation.Shape>())
            {
                if (shape.TextBody == null) continue;

                foreach (var paragraph in shape.TextBody.Descendants<Drawing.Paragraph>())
                {
                    foreach (var run in paragraph.Descendants<Drawing.Run>())
                    {
                        if (run.Text != null && run.Text.Text.Contains(placeholder))
                        {
                            // 检查是否是BeforeText或AfterText，如果是则使用项目符号格式
                            if (placeholder == "[BeforeText]" || placeholder == "[AfterText]")
                            {
                                ReplaceTextWithBulletPoints(slidePart, shape, paragraph, placeholder, newText);
                            }
                            else
                            {
                                run.Text.Text = run.Text.Text.Replace(placeholder, newText ?? "");
                            }
                        }
                    }
                }
            }
        }

       
        //整理好段落格式，PPT才能生成项目符号
        private void ReplaceTextWithBulletPoints(SlidePart slidePart, DocumentFormat.OpenXml.Presentation.Shape shape, 
            Drawing.Paragraph originalParagraph, string placeholder, string newText)
        {
            if (string.IsNullOrEmpty(newText))
            {
                // 如果文本为空，直接替换为空字符串
                foreach (var run in originalParagraph.Descendants<Drawing.Run>())
                {
                    if (run.Text != null && run.Text.Text.Contains(placeholder))
                    {
                        run.Text.Text = run.Text.Text.Replace(placeholder, "");
                    }
                }
                return;
            }

            // 分割文本为多行
            string[] lines = newText.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            
            if (lines.Length == 0) return;

            // 保存原始段落的格式属性
            var originalProperties = originalParagraph.ParagraphProperties;
            var originalRuns = originalParagraph.Descendants<Drawing.Run>().ToList();
            var originalRunProperties = originalRuns.FirstOrDefault()?.RunProperties;

            // 清除原始段落中的所有内容
            originalParagraph.RemoveAllChildren();

            // 恢复原始段落属性
            if (originalProperties != null)
            {
                originalParagraph.ParagraphProperties = originalProperties;
            }

            // 为每一行创建段落
            for (int i = 0; i < lines.Length; i++)
            {
                Drawing.Paragraph paragraph;
                if (i == 0)
                {
                    // 第一行使用原始段落
                    paragraph = originalParagraph;
                }
                else
                {
                    // 后续行创建新段落，复制原始格式
                    paragraph = new Drawing.Paragraph();
                    
                    // 复制原始段落属性（包括项目符号设置）
                    if (originalProperties != null)
                    {
                        paragraph.ParagraphProperties = (Drawing.ParagraphProperties)originalProperties.Clone();
                    }
                    
                    shape.TextBody.Append(paragraph);
                }

                // 创建文本运行，不添加项目符号字符
                Drawing.Run run = new Drawing.Run();
                run.Text = new Drawing.Text(lines[i].Trim());
                
                // 复制原始运行属性（字体、大小等）
                if (originalRunProperties != null)
                {
                    run.RunProperties = (Drawing.RunProperties)originalRunProperties.Clone();
                }
                
                paragraph.Append(run);
            }
        }

        private void ReplaceImagePlaceholder(SlidePart slide, string shapeName, System.Drawing.Image image)
        {
            if (image == null) return;

            var picture = slide.Slide.Descendants<P.Picture>()
                .FirstOrDefault(p => p.NonVisualPictureProperties?.NonVisualDrawingProperties?.Name?.Value == shapeName);

            if (picture == null)
            {
                Console.WriteLine($"❌ 未找到图片占位符: {shapeName}");
                // 输出所有占位符名称以帮助调试
                var allPlaceholders = slide.Slide.Descendants<P.Picture>()
                    .Select(p => p.NonVisualPictureProperties?.NonVisualDrawingProperties?.Name?.Value)
                    .ToList();
                Console.WriteLine("当前占位符名称: " + string.Join(", ", allPlaceholders));
                return;
            }

            // 找到 blip
            var blip = picture.Descendants<D.Blip>().FirstOrDefault();
            if (blip == null)
            {
                Console.WriteLine($"❌ 找不到 Blip 对象: {shapeName}");
                return;
            }

            // 转换图片为字节流
            byte[] imageBytes;
            using (MemoryStream ms = new MemoryStream())
            {
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                imageBytes = ms.ToArray();
            }

            // 添加图片部件
            ImagePart imagePart = slide.AddImagePart(ImagePartType.Png);
            using (MemoryStream ms = new MemoryStream(imageBytes))
            {
                imagePart.FeedData(ms);
            }

            // 替换 Embed 引用
            blip.Embed = slide.GetIdOfPart(imagePart);
            Console.WriteLine($"✅ 成功替换图片: {shapeName}");
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (isDirty)
            {
                DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirm", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    // 用户点击 "是"，调用 ButtonSave_Click 方法
                    btnSave_Click(null, EventArgs.Empty);
                    this.Close();
                }
                else if (result == DialogResult.No)
                {
                    // 用户选择 "否"
                    MessageBox.Show("Not saved!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.Close();
                }

            }
            else 
            {
            this.Close();
            }


        }

        private void projectReport_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (isDirty)
            {
                DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirm", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    // 用户点击 "是"，调用 ButtonSave_Click 方法
                    btnSave_Click(null, EventArgs.Empty);
                }
                else if (result == DialogResult.No)
                {
                    // 用户选择 "否"
                    MessageBox.Show("Not saved!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                { 
                e.Cancel = true;
                }

            }

        }
    }
}